package com.ruoyi.user.identity.controller;

import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.common.IdentityVerification;
import com.ruoyi.user.identity.service.IIdentityVerificationService;
import com.ruoyi.user.user.domain.User;
import com.ruoyi.user.user.service.IUserService;

/**
 * 用户端身份认证Controller
 * 
 * @author slk
 * @date 2025-09-17
 */
@RestController
@RequestMapping("/user/identity")
public class UserIdentityController extends BaseController
{
    @Autowired
    private IIdentityVerificationService identityVerificationService;
    
    @Autowired
    private IUserService userService;

    /**
     * 查询用户身份认证信息
     */
    @GetMapping("/info")
    public AjaxResult getIdentityInfo(@RequestParam Long uid)
    {
        try {
            if (uid == null) {
                return AjaxResult.error("用户ID不能为空");
            }
            
            // 查询身份认证信息
            IdentityVerification identity = identityVerificationService.selectIdentityVerificationByUid(uid);
            
            Map<String, Object> result = new HashMap<>();
            result.put("identity", identity);
            result.put("hasIdentity", identity != null);
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("查询用户身份认证信息失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 保存用户身份认证信息
     */
    @PostMapping("/save")
    public AjaxResult saveIdentityInfo(@RequestBody IdentityVerification identityVerification)
    {
        try {
            System.out.println("=== 身份认证保存调试 ===");
            System.out.println("请求体中的uid: " + identityVerification.getUid());
            System.out.println("姓名: " + identityVerification.getName());
            System.out.println("========================");
            
            // 验证uid是否提供
            if (identityVerification.getUid() == null) {
                return AjaxResult.error("用户ID不能为空");
            }
            
            // 验证用户是否存在
            User user = userService.selectUserById(identityVerification.getUid());
            if (user == null) {
                System.out.println("=== 用户不存在于user表 ===");
                System.out.println("用户ID: " + identityVerification.getUid());
                System.out.println("========================");
                return AjaxResult.error("用户不存在，用户ID: " + identityVerification.getUid());
            }
            
            System.out.println("=== 用户信息验证 ===");
            System.out.println("用户ID: " + user.getId());
            System.out.println("用户手机号: " + user.getPhone());
            System.out.println("====================");
            
            // 保存或更新身份认证信息
            int result = identityVerificationService.saveOrUpdateIdentityVerification(identityVerification);
            
            if (result > 0) {
                return AjaxResult.success("身份认证信息保存成功");
            } else {
                return AjaxResult.error("身份认证信息保存失败");
            }
        } catch (Exception e) {
            logger.error("保存用户身份认证信息失败", e);
            System.out.println("=== 异常详情 ===");
            System.out.println("异常类型: " + e.getClass().getSimpleName());
            System.out.println("异常消息: " + e.getMessage());
            e.printStackTrace();
            System.out.println("================");
            return AjaxResult.error("保存失败：" + e.getMessage());
        }
    }

    /**
     * 查询用户完整信息（头像、姓名、手机号）
     */
    @GetMapping("/profile")
    public AjaxResult getUserProfile(@RequestParam Long uid)
    {
        try {
            if (uid == null) {
                return AjaxResult.error("用户ID不能为空");
            }
            
            // 查询用户基本信息
            User user = userService.selectUserById(uid);
            if (user == null) {
                return AjaxResult.error("用户不存在");
            }
            
            // 查询身份认证信息
            IdentityVerification identity = identityVerificationService.selectIdentityVerificationByUid(uid);
            
            Map<String, Object> result = new HashMap<>();
            result.put("id", user.getId());
            result.put("phone", user.getPhone());
            result.put("avatar", user.getAvatar());
            result.put("regTime", user.getRegTime());
            
            // 如果有身份认证信息，添加姓名
            if (identity != null) {
                result.put("name", identity.getName());
                result.put("hasIdentity", true);
            } else {
                result.put("name", null);
                result.put("hasIdentity", false);
            }
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("查询用户完整信息失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }
}
